<template>
<div class="user">
		<div class="common-form">{{$t('plus.basic_setting')}}</div>
		<div class="product-content">
			<el-form ref="form" :model="form" :rules="formRules" label-width="150px">
				<el-form-item :label="$t('plus.activity_status')" prop="status">
					<el-switch v-model="form.status" active-color="#13ce66" inactive-color="#999999" :active-value="1"
						:inactive-value="0">
					</el-switch>
				</el-form-item>
				<el-form-item :label="$t('plus.activity_start_time')" prop="startTime">
					<el-date-picker style="width: 460px" v-model="form.startTime" type="datetime" :placeholder="$t('plus.activity_start_time')"
						format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
				</el-form-item>
				<el-form-item :label="$t('plus.activity_end_time')" prop="endTime">
					<el-date-picker style="width: 460px" v-model="form.endTime" type="datetime" :placeholder="$t('plus.activity_end_time')"
						format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
				</el-form-item>
				<el-form-item :label="$t('plus.participants')" :rules="[{  required: true,  message: ''}]" prop="userType">
					<div>
						<el-radio-group v-model="form.userType" @change="changeUserType">
							<el-radio :label="0">{{$t('plus.all_users')}}</el-radio>
							<el-radio :label="1">{{$t('plus.partial_users')}}</el-radio>
						</el-radio-group>
					</div>
					<div v-if="form.userType == 1">
						<el-select v-model="form.gradeIdList" style="width: 460px" multiple :placeholder="$t('plus.please_select')"
							size="small">
							<el-option v-for="(item, index) in Grade" :key="index" :label="item.name"
								:value="item.gradeId"></el-option>
						</el-select>
					</div>
				</el-form-item>
				<el-form-item :label="$t('plus.daily_draw_limit')" prop="times" :rules="[{  required: true,  message: ' '}]">
					<el-input type="text" v-model="form.times" :placeholder="$t('plus.input_daily_draw_limit')" class="max-w460"></el-input>
				</el-form-item>
				<el-form-item :label="$t('plus.total_draw_limit')" prop="totalNum" :rules="[{  required: true,  message: ' '}]">
					<el-input type="text" v-model="form.totalNum" :placeholder="$t('plus.input_total_draw_limit')" class="max-w460"></el-input>
				</el-form-item>
				<el-form-item :label="$t('plus.points_per_draw')" prop="points" :rules="[{  required: true,  message: ' '}]">
					<el-input type="text" v-model="form.points" :placeholder="$t('plus.input_points_per_draw')" class="max-w460"></el-input>
				</el-form-item>
				<el-form-item :label="$t('plus.activity_bg')" prop="filePath">
					<el-row>
						<el-button type="primary" @click="openUpload" size="small">{{$t('plus.choose_image')}}</el-button>
						<div v-if="form.filePath != ''" class="img">
							<img :src="form.filePath" width="100" height="100" />
						</div>
						<view class="tips">{{$t('plus.bg_size_tip')}}</view>
					</el-row>
				</el-form-item>

				<div class="common-form">{{$t('plus.gift_config')}}</div>
				<!-- <el-form-item label="" v-if="tableData.length < 8">
          <el-button type="primary" @click="addCoupon()">添加优惠券</el-button>
          <el-button type="primary" @click="addProduct()">添加商品</el-button>
          <el-button type="primary" @click="addPoint()">添加积分</el-button>
          <el-button type="primary" @click="addNothing()">添加空项</el-button>
        </el-form-item> -->
				<el-form-item :label="$t('plus.rule_selection')" :rules="[{  required: true,  message: ' '}]">
					<div class="d-b-s">
						<div>
							<div class="table-head"></div>
							<draggable v-model="tableData" tag="ul" item-key="index">
								<template #item="{  element,  index}">
									<li class="table-no">
										<!-- <span>{{ index + 1 }}</span> -->
										<el-icon>
											<Rank />
										</el-icon>
									</li>
								</template>
							</draggable>
						</div>

						<el-table :data="tableData" @current-change="handleCurrentChange" ref="singleTable">
							<el-table-column prop="sort" :label="$t('plus.serial_number')" type="index"></el-table-column>
							<el-table-column prop="image" :label="$t('plus.image')" :width="80">
								<template #default="scope">
									<img v-img-url="hasImages(scope.row.image)" alt="" :width="50" :height="50" />
								</template>
							</el-table-column>
							<el-table-column prop="name" :label="$t('plus.name')">
								<template #default="scope">
									<div style="white-space: nowrap" class="text-ellipsis">
										{{scope.row.name}}
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="type" :label="$t('plus.type')">
								<template #default="scope">
									<span v-if="scope.row.type == 0">{{$t('plus.no_gift')}}</span>
									<span v-if="scope.row.type == 1">{{$t('plus.coupon')}}</span>
									<span v-if="scope.row.type == 2">{{$t('plus.gift_point')}}</span>
									<span v-if="scope.row.type == 3">{{$t('plus.gift_product')}}</span>
									<span v-if="scope.row.type == 4">{{$t('plus.balance')}}</span>
								</template>
							</el-table-column>
							<el-table-column prop="prompt" :label="$t('plus.hint_text')">
								<template #default="scope">
									<div style="white-space: nowrap" class="text-ellipsis">
										{{scope.row.prompt}}
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="stock" :label="$t('plus.activity_stock')"></el-table-column>
							<el-table-column prop="drawNum" :label="$t('plus.gift_sent')"></el-table-column>
							<el-table-column prop="weight" :label="$t('plus.prize_weight')"></el-table-column>
							<el-table-column prop="isDefault" :label="$t('plus.prize_probability')" :rules="[{  required: true,  message: ' '}]">
								<template #default="scope">
									{{probability(scope.row.weight)}}% 
</template>
							</el-table-column>
							<el-table-column prop="isDefault" :label="$t('plus.is_default')" :rules="[{  required: true,  message: ' '}]">
								<template #default="scope">
									<el-switch @change="changeSwitch(scope.row)" :model-value="scope.row.isDefault == 1"
										active-color="#13ce66" inactive-color="#999999">
									</el-switch>
								</template>
							</el-table-column>
							<el-table-column prop="isPlay" :label="$t('plus.is_announce')">
								<!-- 0 不播报 1 播报 -->
								<template #default="scope">
									<el-switch v-model="scope.row.isPlay" active-color="#13ce66" :active-value="1"
										:inactive-value="0" inactive-color="#999999">
									</el-switch>
								</template>
							</el-table-column>
							<el-table-column prop="address" :label="$t('plus.action')">
								<template #default="scope">
									<el-button type="primary" link size="small"
										@click="editFunc(scope.row, scope.$index)">{{$t('plus.edit')}}</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</el-form-item>
				<view class="tips" style="margin-left:150px;">{{$t('plus.prize_note')}} 
</view>
				<el-form-item :label="$t('plus.activity_rule')" prop="content" :rules="[{  required: true,  message: ' '}]">
					<WangEditor style="width: 100%" :content="form.content" @contens="contentm"
						@editorContent="getEditorContent"></WangEditor>
					<!-- <el-input
            type="textarea"
            :rows="3"
            v-model="form.content"
            placeholder="请输入活动规则"
            class="max-w460"
          ></el-input> -->
				</el-form-item>
			</el-form>
			<!--提交-->
			<div class="common-button-wrapper">
				<el-button type="info" @click="gotoBack">{{$t('plus.back')}}</el-button>
				<el-button type="primary" @click="onSubmit" :loading="loading">{{$t('plus.submit')}}</el-button>
			</div>
		</div>
		<el-dialog :title="$t('plus.add_points')" v-model="isPoint">
			<el-input v-model="point" autocomplete="off"></el-input>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="closePointFunc(false)">{{$t('plus.cancel')}}</el-button>
					<el-button type="primary" @click="closePointFunc(true)">{{$t('plus.confirm')}}</el-button>
				</div>
			</template>
		</el-dialog>
		<!--上传图片组件-->
		<Upload v-if="isupload" :isupload="isupload" :type="type" @returnImgs="returnImgsFunc">{{$t('plus.upload_image_button')}}</Upload>
		<EditDialog :model="formModel" v-if="isEdit" @closeDialog="closeEdit"></EditDialog>
		<!--选择优惠券-->
		<!-- <GetCoupon v-if="open_add" :open_add="open_add" @closeDialog="closeProductDialogFunc($event)">选择优惠券弹出层 -->
		<!-- </GetCoupon> -->
		<!--选择商品-->
		<!-- <Product :isProduct="isProduct" :excludeIds="excludeIds" :islist="false" @closeDialog="closeProductFunc"> -->
		<!-- </Product> -->
	</div>
</template>

<script>
import UserApi from "@/api/user.js";
import LotteryApi from "@/api/lottery.js";
import EditDialog from "./dialog/edit.vue";
// import GetCoupon from "@/components/coupon/GetCoupon.vue";
// import Product from "@/components/product/Product.vue";
import Upload from "@/components/file/Upload.vue";
import draggable from "vuedraggable";
import WangEditor from "@/components/wangEditor/index.vue";
import { formatModel } from "@/utils/base.js";
export default {
  components: {
    /*选择优惠券件*/
    // GetCoupon,
    // Product,
    Upload,
    EditDialog,
    draggable,
    WangEditor
  },
  data() {
    return {
      form: {
        prize: [],
        points: 0,
        isTimes: 0,
        couponNum: 1,
        times: "",
        name: "",
        lotteryId: 0,
        imageId: "",
        content: "",
        filePath: "",
        status: 0,
        type: 0,
        userType: 0,
        gradeIdList: [],
        startTime: "",
        endTime: "",
        totalNum: ""
      },
      filePath: "",
      Grade: {},
      tableData: [],
      loading: false,
      open_add: false,
      /*是否打开选择商品*/
      isProduct: false,
      excludeIds: [],
      spec_type: 10,
      /*是否打开图片选择*/
      isupload: false,
      formRules: {
        filePath: [{
          required: true,
          message: $t("plus.upload_bg"),
          trigger: "blur"
        }]
      },
      /*左边长度*/
      formLabelWidth: "120px",
      isPoint: false,
      point: "",
      isNothing: false,
      isLottery: -1,
      prizeIds: [],
      isEdit: false,
      formModel: null,
      formIndex: 0
    };
  },
  created() {
    /*获取等级*/
    this.getGradeList();
    /*获取数据*/
    this.getData();
  },
  methods: {
    contentm(e) {
      this.form.content = e;
    },
    getEditorContent(data) {
      this.form.content = data;
    },
    changeUserType(e) {
      this.form.gradeIdList = [];
    },
    probability(n) {
      const totalWeight = this.tableData.reduce((sum, item) => sum + item.weight * 1, 0);
      if (!totalWeight) {
        return 0;
      } else {
        return (n / totalWeight * 100).toFixed(2);
      }
    },
    editFunc(e, n) {
      this.formIndex = n;
      this.formModel = JSON.parse(JSON.stringify(e));
      console.log(this.formModel);
      this.isEdit = true;
    },
    closeEdit(e) {
      this.isEdit = false;
      console.log(e);
      if (e.type == "success") {
        this.tableData[this.formIndex] = e.form;
      }
    },
    hasImages(e) {
      if (e) {
        return e;
      } else {
        return "";
      }
    },
    /*添加优惠券*/
    addCoupon() {
      this.open_add = true;
    },
    /*关闭优惠券*/
    closeProductDialogFunc(e) {
      let self = this;
      self.open_add = e.openDialog;
      if (e.type == "success") {
        let params = {
          prizeId: 0,
          awardId: e.params.couponId,
          name: e.params.name,
          stock: 1,
          type: 1,
          image: "",
          points: 0,
          isDefault: 0
        };
        self.tableData.push(params);
      }
    },
    /*添加商品*/
    addProduct() {
      let params = {
        prizeId: 0,
        awardId: 0,
        name: $t("plus.input_product_name"),
        stock: 1,
        type: 3,
        image: "",
        points: 0,
        isDefault: 0
      };
      this.tableData.push(params);
    },
    /*关闭商品*/
    closeProductFunc(e) {
      let self = this;
      self.isProduct = e.openDialog;
      if (e.type == "success") {
        let params = {
          prizeId: 0,
          awardId: e.params.productId,
          name: e.params.productName,
          stock: 1,
          type: 3,
          image: e.params.productImage,
          points: 0,
          isDefault: 0
        };
        self.tableData.push(params);
      }
    },
    addPoint() {
      this.isPoint = true;
    },
    closePointFunc(e) {
      let self = this;
      self.isPoint = e.openDialog;
      let points = this.point;
      if (e) {
        let params = {
          prizeId: 0,
          awardId: 0,
          name: $t("plus.gift_point"),
          points: 0,
          stock: 1,
          type: 2,
          image: "",
          isDefault: 0
        };
        params.points = points;
        params.name = points + $t("plus.gift_point");
        self.tableData.push(params);
      }
    },
    addNothing() {
      let self = this;
      let params = {
        prizeId: 0,
        awardId: 0,
        name: $t("plus.good_luck"),
        stock: 1,
        type: 0,
        image: "",
        points: 0,
        isDefault: 0
      };
      self.tableData.push(params);
    },
    /*获取等级*/
    getGradeList() {
      let self = this;
      let Params = {};
      Params.page = self.curPage;
      Params.list_rows = self.pageSize;
      UserApi.gradelist(Params, true).then(data => {
        self.Grade = data.data.records;
      }).catch(error => {});
    },
    /*获取数据*/
    getData() {
      let self = this;
      LotteryApi.getData(true).then(res => {
        if (res.data.userType == null) {
          res.data.userType = 0;
        }
        self.form = formatModel(self.form, res.data);
        if (self.form.prize != null) {
          self.tableData = JSON.parse(JSON.stringify(self.form.prize));
          if (this.tableData.length == 0) {
            for (let i = 0; i < 8; i++) {
              this.tableData.push({
                sort: "",
                image: "",
                name: "",
                type: "",
                prompt: "",
                stock: "",
                drawNum: "",
                weight: "",
                isDefault: 0,
                isPlay: 0,
                address: ""
              });
            }
          }
          self.prizeIds = [];
        }
      }).catch(error => {});
    },
    delProduct(item) {
      let self = this;
      let n = self.prodcutData.indexOf(item);
      self.prodcutData.splice(n, 1);
      self.form.product.splice(n, 1);
    },
    // delcoupon(item) {
    // 	let self = this;
    // 	let n = self.tableData.indexOf(item);
    // 	if (item.prizeId) {
    // 		self.prizeIds = [...self.prizeIds, item.prizeId];
    // 	}
    // 	self.tableData.splice(n, 1);
    // },
    /*提交表单*/
    onSubmit() {
      let self = this;
      let form = self.form;
      if (self.tableData.length != 8) {
        ElMessage.error($t("plus.set_8_gifts"));
        return;
      }
      if (!self.form.content) {
        ElMessage.error($t("plus.fill_activity_rule"));
      }
      let flag = false;
      self.tableData.forEach((item, index) => {
        if (item.isDefault == 1) {
          flag = true;
          return;
        }
      });
      if (!flag) {
        ElMessage.error($t("plus.set_default"));
        return;
      }
      let list = [];
      console.log(form.prize);
      console.log(self.tableData);
      // 用于快速查找数组 a 中的 id
      /* 原数组id */
      // const oldIds = new Set(form.prize.map(item => item.prizeId));
      const newIds = new Set(self.tableData.map(item => item.prizeId));
      // 遍历数组 newIds，检查每个子集的 prizeId 是否在数组 oldIds 中存在
      // for (const item of self.tableData) {
      // 	if (!oldIds.has(item.prizeId)) {
      // 		list.push(item);
      // 	}
      // }
      // 遍历数组 a，检查每个子集的 id 是否在数组 b 中存在
      for (const item of form.prize) {
        if (!newIds.has(item.prizeId)) {
          list.push(item.prizeId);
        }
      }
      console.log(list);
      const updatedList = self.tableData.map((item, index) => {
        // 创建一个新对象，以避免直接修改原始对象
        return {
          ...item,
          sort: index
        };
      });
      form.prizeIds = list;
      form.prize = updatedList;
      self.$refs.form.validate(valid => {
        if (valid) {
          self.loading = true;
          LotteryApi.EditLottery(form, true).then(data => {
            self.loading = false;
            if (data.code == 1) {
              ElMessage({
                message: data.msg,
                type: "success"
              });
              self.getData();
              // self.$router.push('/plus/lottery/index');
            } else {
              self.loading = false;
            }
          }).catch(error => {
            self.loading = false;
          });
        }
      });
    },
    changeImg(e) {
      this.isLottery = this.tableData.indexOf(e);
      this.isupload = true;
    },
    /*上传*/
    openUpload(e) {
      this.type = e;
      this.isupload = true;
    },
    /*获取图片*/
    returnImgsFunc(e) {
      if (e != null && e.length > 0) {
        if (this.isLottery != -1) {
          this.tableData[this.isLottery].image = e[0].filePath;
        } else {
          this.form.filePath = e[0].filePath;
          this.form.imageId = e[0].fileId;
        }
      }
      this.isLottery = -1;
      this.isupload = false;
    },
    /*返回上一页面*/
    gotoBack() {
      this.$router.back(-1);
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    changeSwitch(row) {
      this.tableData.forEach((item, index) => {
        item.isDefault = 0;
      });
      row.isDefault = 1;
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell {
		background: none;
	}

	.table-head {
		height: 48.8px;
		border: 1px solid #eee;
		background-color: #eaedf4;
		width: 80px;
		display: flex;
		// justify-content: center;
		align-items: center;
		box-sizing: border-box;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: normal;
		word-break: break-all;
		font-weight: 600;
		padding: 0 12px;
		line-height: 32px !important;
		font-size: 12px !important;
		color: #101010 !important;
	}

	.table-no {
		padding: 8px 0;
		min-width: 0;
		box-sizing: border-box;
		text-overflow: ellipsis;
		vertical-align: middle;
		position: relative;
		text-align: left;
		height: 66.8px;
		//border-bottom: 1px solid #eee;
		width: 80px;
		display: flex;
		// justify-content: center;
		align-items: center;
		box-sizing: border-box;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: normal;
		word-break: break-all;
		font-weight: 600;
		padding: 0 12px;
		line-height: 32px !important;
		font-size: 12px !important;
		color: #101010 !important;
		cursor: all-scroll;
	}
</style>

